<template>
  <div class="chat-content" ref="chatContent" @scroll="handleScroll">
    <!-- 聊天消息列表容器 -->
    <div ref="messageListRef" class="message-list" @scroll="handleScroll">
      <!-- 聊天消息列表，包括机器人和用户 -->
      <template v-for="(msg, idx) in messages" :key="idx">
        <div v-if="msg.role === 'ai'" class="message ai-message">
          <el-icon class="avatar"><Service /></el-icon>
          <div class="message-content">{{ msg.content }}</div>
        </div>
        <div v-else-if="msg.role === 'user'" class="message user-message">
          <div class="message-content">{{ msg.content }}</div>
          <el-icon class="avatar user-avatar"><Service /></el-icon>
        </div>
      </template>
    </div>
    <!-- ChatInput component with bottom margin -->
    <div class="input-container">
      <ChatInput @send="handleSend" :scrollPercentage="scrollPercentage" :isRobotTyping="isRobotTyping" />
    </div>
  </div>
</template>

<script setup>
import { Service } from '@element-plus/icons-vue'
import ChatInput from './ChatInput.vue'
import { ref, watch, nextTick } from 'vue'
import { robotAnswers } from '../../robotAnswers.js'

const props = defineProps({
  messages: {
    type: Array,
    required: true
  }
})

const emit = defineEmits(['send-message'])
const chatContent = ref(null)
const scrollPercentage = ref(0)
const isRobotTyping = ref(false)

let shouldScrollToEndAfterTyping = false; // New variable to track if we should scroll after typing

const handleScroll = () => {
  const element = messageListRef.value;
  if (element) {
    const { scrollTop, scrollHeight, clientHeight } = element;
    const maxScroll = scrollHeight - clientHeight;
    scrollPercentage.value = maxScroll > 0 ? Math.round((scrollTop / maxScroll) * 100) : 0;
  }
}

const messages = ref([
  { role: 'ai', content: '请问有什么问题可以帮助你吗？' }
])

// Create a ref for the message list element
const messageListRef = ref(null)

function handleSend(msg) {
  if (isRobotTyping.value) return
  messages.value.push({ role: 'user', content: msg })
  // 机器人流水式自动回复
  const idx = Math.floor(Math.random() * robotAnswers.length)
  streamRobotReply(robotAnswers[idx])
  // After sending a message, always auto-scroll to see the user's message immediately
  nextTick(scrollToBottom);
}

// 通用流式机器人回复方法
function streamRobotReply(answer) {
  isRobotTyping.value = true

  // Check if user is at the bottom BEFORE typing starts
  const element = messageListRef.value;
  if (element) {
     const { scrollTop, scrollHeight, clientHeight } = element;
     shouldScrollToEndAfterTyping = (scrollTop + clientHeight + 10) >= scrollHeight; // Add a small buffer
  } else {
     shouldScrollToEndAfterTyping = true; // Default to true if element not available yet
  }

  let current = ''
  messages.value.push({ role: 'ai', content: '' })
  const aiIdx = messages.value.length - 1
  let i = 0
  function nextChar() {
    if (i < answer.length) {
      current += answer[i]
      messages.value[aiIdx].content = current
      i++
      setTimeout(nextChar, 40)
    } else {
       // Scroll to bottom ONLY if user was at the bottom when typing started
       if (shouldScrollToEndAfterTyping) {
          nextTick(scrollToBottom)
       }
       isRobotTyping.value = false
    }
  }
  nextChar()
}

// Function to scroll the message list to the bottom
function scrollToBottom() {
  const element = messageListRef.value
  // Always scroll to bottom when called (logic to decide *when* to call is elsewhere)
  if (element) {
    element.scrollTop = element.scrollHeight
  }
}

// Watch for changes in the messages array
// This watch no longer forces scroll, it just reacts to message updates if needed later
watch(messages, () => {
  // If needed, add logic here for other scenarios that require scrolling, but not for robot streaming
}, { deep: true }) // Use deep: true to watch for changes within the array items
</script>

<style scoped>
.chat-content {
  flex: 1;
  padding: 0 20px; /* Padding around the entire chat area */
  overflow: hidden; /* Prevent main chat-content from scrolling */
  width: 1000px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  height: 100%; /* Make sure chat-content fills its parent height */
}

.message-list {
  flex: 1; /* Take up all available space */
  overflow-y: auto; /* Make message list scrollable */
  padding: 20px 0; /* Padding within the scrollable message area */
  /* Removed margin-bottom */
  /* Hide scrollbar - REMOVED */
  /* -ms-overflow-style: none; */
  /* scrollbar-width: none; */
}

/* Removed hiding for Chrome, Safari, Opera scrollbar */
/* .message-list::-webkit-scrollbar { */
  /* display: none; */
/* } */

/* Custom scrollbar styles */
.message-list::-webkit-scrollbar {
  width: 6px;  /* Set the width of the scrollbar */
}

.message-list::-webkit-scrollbar-thumb {
  background-color: rgba(0, 0, 0, 0.2); /* Set the color of the scrollbar thumb (lighter black/gray) */
  border-radius: 3px; /* Optional: round the corners of the thumb */
}

.message-list::-webkit-scrollbar-track {
  background-color: rgba(0, 0, 0, 0.05); /* Optional: set the color of the track */
}

.message {
  margin-bottom: 20px;
  display: flex;
  align-items: flex-start;
}

.avatar {
  font-size: 24px;
}

.ai-message .avatar {
  margin-right: 12px;
  color: #409eff;
}

.user-message {
  flex-direction: column;
  align-items: flex-end;
  position: relative;
  right: 10px;
}

.user-avatar {
  margin-left: 12px;
  color: #67c23a;
  position: absolute;
  top: 0;
}

.message-content {
  background-color: #fff;
  padding: 12px 16px;
  border-radius: 8px;
  max-width: 80%;
  margin-right: 36px;
  word-wrap: break-word; /* Ensure long words break and wrap */
  overflow-wrap: break-word; /* Standard property */
  white-space: pre-wrap; /* Preserve whitespace and allow wrapping */
}

.user-message .message-content {
  background-color: #e5f2ff;
  margin-bottom: 10px;
}

.options {
  margin-top: 10px;
}

.options .el-button {
  margin-right: 10px;
}

/* New container for the input with bottom spacing */
.input-container {
  margin-bottom: 20px; /* Additional space at the bottom */
  position: relative; /* Make this a positioning context for absolute children */
}
</style>